<template>
  <view class="seckill-detail-container">
    <!-- 活动头部信息 -->
    <view class="activity-header">
      <image 
        :src="activityDetail.bannerImage || activityDetail.image" 
        class="activity-banner"
        mode="aspectFill"
      />
      <view class="activity-info">
        <text class="activity-title">{{ activityDetail.title }}</text>
        <text class="activity-desc">{{ activityDetail.description }}</text>
        
        <!-- 倒计时 -->
        <view class="countdown" v-if="getActivityStatus() === 'ongoing'">
          <text class="countdown-label">距结束还剩：</text>
          <view class="countdown-time">
            <text class="time-item">{{ countdown.hours }}</text>
            <text class="time-separator">:</text>
            <text class="time-item">{{ countdown.minutes }}</text>
            <text class="time-separator">:</text>
            <text class="time-item">{{ countdown.seconds }}</text>
          </view>
        </view>
        <view class="countdown" v-else-if="getActivityStatus() === 'upcoming'">
          <text class="countdown-label">距开始还剩：</text>
          <view class="countdown-time">
            <text class="time-item">{{ countdown.hours }}</text>
            <text class="time-separator">:</text>
            <text class="time-item">{{ countdown.minutes }}</text>
            <text class="time-separator">:</text>
            <text class="time-item">{{ countdown.seconds }}</text>
          </view>
        </view>
        
        <view class="activity-time">
          <text class="time-label">活动时间：</text>
          <text class="time-value">{{ formatTime(activityDetail.startTime) }} - {{ formatTime(activityDetail.endTime) }}</text>
        </view>
        <view class="activity-status">
          <text class="status-text" :class="getActivityStatus()">{{ getStatusText(getActivityStatus()) }}</text>
        </view>
      </view>
    </view>

    <!-- 活动规则 -->
    <view class="activity-rules" v-if="activityDetail.rules">
      <view class="section-title">活动规则</view>
      <view class="rules-content">
        <text class="rules-text">{{ activityDetail.rules }}</text>
      </view>
    </view>

    <!-- 商品列表 -->
    <view class="products-section">
      <view class="section-title">秒杀商品</view>
      <view class="products-grid">
        <view 
          v-for="product in productList" 
          :key="product.id"
          class="product-item"
          @click="goToProduct(product.id)"
        >
          <image 
            :src="product.image" 
            class="product-image"
            mode="aspectFill"
          />
          <view class="product-info">
            <text class="product-title">{{ product.name || product.title }}</text>
            <view class="product-price">
              <text class="seckill-price">¥{{ product.seckillPrice || product.currentPrice }}</text>
              <text class="original-price" v-if="product.originalPrice">¥{{ product.originalPrice }}</text>
            </view>
            <view class="product-stats">
              <text class="stock-info">库存: {{ product.stock || 0 }}</text>
              <text class="sold-info">已售: {{ product.soldCount || 0 }}</text>
            </view>
            <view class="product-tags" v-if="product.tags && product.tags.length">
              <text 
                v-for="tag in product.tags" 
                :key="tag"
                class="tag"
              >{{ tag }}</text>
            </view>
            <view class="product-actions">
              <button 
                v-if="getActivityStatus() === 'ongoing'"
                class="action-btn seckill-btn" 
                @click.stop="goToSeckill(activityDetail.id, product.id)"
              >
                立即秒杀
              </button>
              <button 
                v-else-if="getActivityStatus() === 'upcoming'"
                class="action-btn remind-btn" 
                @click.stop="setReminder(activityDetail.id)"
              >
                设置提醒
              </button>
              <button 
                v-else
                class="action-btn ended-btn" 
                disabled
              >
                已结束
              </button>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 活动统计 -->
    <view class="activity-stats" v-if="activityStats">
      <view class="section-title">活动统计</view>
      <view class="stats-grid">
        <view class="stat-item">
          <text class="stat-number">{{ activityStats.totalParticipants }}</text>
          <text class="stat-label">参与人数</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ activityStats.totalSales }}</text>
          <text class="stat-label">销售总额</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ activityStats.totalOrders }}</text>
          <text class="stat-label">订单数量</text>
        </view>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-actions">
      <button class="share-btn" @click="shareActivity">分享活动</button>
      <button 
        v-if="getActivityStatus() === 'ongoing'"
        class="join-btn" 
        @click="goToSeckill(activityDetail.id)"
      >
        立即参与
      </button>
      <button 
        v-else-if="getActivityStatus() === 'upcoming'"
        class="join-btn" 
        @click="setReminder(activityDetail.id)"
      >
        设置提醒
      </button>
      <button 
        v-else
        class="join-btn ended" 
        disabled
      >
        活动已结束
      </button>
    </view>

    <!-- 加载状态 -->
    <view class="loading-container" v-if="loading">
      <uni-load-more status="loading" />
    </view>
  </view>
</template>

<script>
import { getSeckillDetail, getSeckillProducts, setSeckillReminder } from '@/api/seckill'

export default {
  name: 'SeckillDetailPage',
  data() {
    return {
      activityId: null,
      loading: false,
      activityDetail: {},
      productList: [],
      activityStats: null,
      countdown: {
        hours: '00',
        minutes: '00',
        seconds: '00'
      },
      countdownTimer: null
    }
  },
  
  onLoad(options) {
    this.activityId = options.id
    if (this.activityId) {
      this.loadActivityDetail()
    }
  },
  
  onUnload() {
    // 清除倒计时定时器
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer)
    }
  },
  
  methods: {
    // 加载活动详情和商品列表
    async loadActivityDetail() {
      try {
        this.loading = true
        const response = await getSeckillDetail(this.activityId)
        this.activityDetail = response.data || {}
        
        // 从活动详情中提取商品列表
        this.productList = this.activityDetail.products || []
        
        // 根据活动状态开始倒计时
        const status = this.getActivityStatus()
        if (status === 'ongoing' || status === 'upcoming') {
          this.startCountdown()
        }
        
        console.log('活动详情:', this.activityDetail)
        console.log('商品列表:', this.productList)
      } catch (error) {
        console.error('加载活动详情失败:', error)
        uni.showToast({
          title: '加载活动详情失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 开始倒计时
    startCountdown() {
      this.updateCountdown()
      this.countdownTimer = setInterval(() => {
        this.updateCountdown()
      }, 1000)
    },
    
    // 更新倒计时
    updateCountdown() {
      const status = this.getActivityStatus()
      
      if (status === 'ongoing') {
        // 活动进行中，倒计时到结束
        if (!this.activityDetail.endTime) return
        
        const now = new Date().getTime()
        const end = new Date(this.activityDetail.endTime).getTime()
        const diff = Math.max(0, end - now)
        
        if (diff <= 0) {
          // 活动结束
          if (this.countdownTimer) {
            clearInterval(this.countdownTimer)
          }
          return
        }
        
        const hours = Math.floor(diff / (1000 * 60 * 60))
        const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
        const seconds = Math.floor((diff % (1000 * 60)) / 1000)
        
        this.countdown = {
          hours: hours.toString().padStart(2, '0'),
          minutes: minutes.toString().padStart(2, '0'),
          seconds: seconds.toString().padStart(2, '0')
        }
      } else if (status === 'upcoming') {
        // 活动即将开始，倒计时到开始
        if (!this.activityDetail.startTime) return
        
        const now = new Date().getTime()
        const start = new Date(this.activityDetail.startTime).getTime()
        const diff = Math.max(0, start - now)
        
        if (diff <= 0) {
          // 活动开始，重新计算倒计时
          this.updateCountdown()
          return
        }
        
        const hours = Math.floor(diff / (1000 * 60 * 60))
        const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
        const seconds = Math.floor((diff % (1000 * 60)) / 1000)
        
        this.countdown = {
          hours: hours.toString().padStart(2, '0'),
          minutes: minutes.toString().padStart(2, '0'),
          seconds: seconds.toString().padStart(2, '0')
        }
      }
    },
    
    // 格式化时间
    formatTime(timeStr) {
      if (!timeStr) return ''
      const date = new Date(timeStr)
      const month = date.getMonth() + 1
      const day = date.getDate()
      const hour = date.getHours()
      const minute = date.getMinutes()
      return `${month}-${day} ${hour}:${minute}`
    },
    
    // 根据时间判断活动状态
    getActivityStatus() {
      if (!this.activityDetail.startTime || !this.activityDetail.endTime) {
        return 'unknown'
      }
      
      const now = new Date().getTime()
      const startTime = new Date(this.activityDetail.startTime).getTime()
      const endTime = new Date(this.activityDetail.endTime).getTime()
      
      if (now < startTime) {
        return 'upcoming' // 即将开始
      } else if (now >= startTime && now <= endTime) {
        return 'ongoing' // 进行中
      } else {
        return 'ended' // 已结束
      }
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        'upcoming': '即将开始',
        'ongoing': '进行中',
        'ended': '已结束',
        'unknown': '未知'
      }
      return statusMap[status] || '未知'
    },
    
    // 跳转到商品详情
    goToProduct(productId) {
      uni.navigateTo({
        url: `/pages/seckill/productdetail?id=${productId}`
      })
    },
    
    // 跳转到秒杀页面
    goToSeckill(activityId, productId = null) {
      let url = `/pages/seckill/seckill?id=${activityId}`
      if (productId) {
        url += `&productId=${productId}`
      }
      uni.navigateTo({ url })
    },
    
    // 设置提醒
    async setReminder(activityId) {
      try {
        const response = await setSeckillReminder({
          activityId: activityId
        })
        
        if (response.code === 200) {
          uni.showToast({
            title: '提醒设置成功',
            icon: 'success'
          })
        } else {
          uni.showToast({
            title: response.message || '设置失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('设置提醒失败:', error)
        uni.showToast({
          title: '设置提醒失败',
          icon: 'none'
        })
      }
    },
    
    // 分享活动
    shareActivity() {
      uni.showToast({
        title: '分享功能开发中',
        icon: 'none'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.seckill-detail-container {
  min-height: 100vh;
  background: #f5f6f7;
  padding-bottom: 120rpx;
}

.activity-header {
  background: linear-gradient(135deg, #ff6b6b 0%, #ff8e8e 100%);
  color: white;
  padding: 30rpx;
  
  .activity-banner {
    width: 100%;
    height: 300rpx;
    border-radius: 16rpx;
    margin-bottom: 30rpx;
  }
  
  .activity-info {
    .activity-title {
      font-size: 36rpx;
      font-weight: bold;
      margin-bottom: 16rpx;
      display: block;
    }
    
    .activity-desc {
      font-size: 28rpx;
      opacity: 0.9;
      margin-bottom: 20rpx;
      display: block;
      line-height: 1.5;
    }
    
    .countdown {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;
      
      .countdown-label {
        font-size: 26rpx;
        margin-right: 16rpx;
      }
      
      .countdown-time {
        display: flex;
        align-items: center;
        
        .time-item {
          background: rgba(255, 255, 255, 0.2);
          padding: 8rpx 12rpx;
          border-radius: 8rpx;
          font-size: 24rpx;
          font-weight: bold;
          min-width: 40rpx;
          text-align: center;
        }
        
        .time-separator {
          margin: 0 8rpx;
          font-size: 24rpx;
          font-weight: bold;
        }
      }
    }
    
    .activity-time {
      display: flex;
      align-items: center;
      margin-bottom: 16rpx;
      
      .time-label {
        font-size: 26rpx;
        margin-right: 8rpx;
      }
      
      .time-value {
        font-size: 26rpx;
        opacity: 0.9;
      }
    }
    
    .activity-status {
      display: flex;
      justify-content: flex-start;
      
      .status-text {
        font-size: 24rpx;
        padding: 8rpx 16rpx;
        border-radius: 20rpx;
        background: rgba(255, 255, 255, 0.2);
        
        &.ongoing {
          background: #52c41a;
        }
        
        &.upcoming {
          background: #fa8c16;
        }
        
        &.ended {
          background: #999;
        }
      }
    }
  }
}

.activity-rules {
  background: white;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
  
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }
  
  .rules-content {
    .rules-text {
      font-size: 28rpx;
      color: #666;
      line-height: 1.6;
    }
  }
}

.products-section {
  background: white;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
  
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }
  
  .products-grid {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
  }
  
  .product-item {
    display: flex;
    background: #f8f9fa;
    border-radius: 12rpx;
    padding: 20rpx;
    transition: all 0.3s;
    
    &:active {
      transform: scale(0.98);
    }
    
    .product-image {
      width: 120rpx;
      height: 120rpx;
      border-radius: 8rpx;
      margin-right: 20rpx;
    }
    
    .product-info {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      
      .product-title {
        font-size: 28rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 12rpx;
        line-height: 1.4;
      }
      
      .product-price {
        display: flex;
        align-items: center;
        margin-bottom: 12rpx;
        
        .seckill-price {
          font-size: 32rpx;
          font-weight: bold;
          color: #ff4757;
          margin-right: 12rpx;
        }
        
        .original-price {
          font-size: 24rpx;
          color: #999;
          text-decoration: line-through;
        }
      }
      
      .product-stats {
        display: flex;
        justify-content: space-between;
        margin-bottom: 12rpx;
        font-size: 22rpx;
        color: #666;
        
        .stock-info {
          color: #52c41a;
        }
        
        .sold-info {
          color: #ff4757;
        }
      }
      
      .product-tags {
        display: flex;
        gap: 8rpx;
        margin-bottom: 12rpx;
        
        .tag {
          font-size: 20rpx;
          padding: 4rpx 8rpx;
          background: #ff4757;
          color: white;
          border-radius: 4rpx;
        }
      }
      
      .product-actions {
        display: flex;
        gap: 12rpx;
        
        .action-btn {
          flex: 1;
          font-size: 24rpx;
          padding: 12rpx 0;
          border-radius: 8rpx;
          border: none;
          
          &.seckill-btn {
            background: #ff4757;
            color: white;
          }
          
          &.remind-btn {
            background: #fa8c16;
            color: white;
          }
          
          &.ended-btn {
            background: #999;
            color: white;
          }
        }
      }
    }
  }
}

.activity-stats {
  background: white;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
  
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }
  
  .stats-grid {
    display: flex;
    justify-content: space-around;
    
    .stat-item {
      text-align: center;
      
      .stat-number {
        display: block;
        font-size: 36rpx;
        font-weight: bold;
        color: #ff4757;
        margin-bottom: 8rpx;
      }
      
      .stat-label {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #eee;
  display: flex;
  gap: 20rpx;
  
  .share-btn {
    flex: 1;
    background: #f5f5f5;
    color: #666;
    border: none;
    border-radius: 8rpx;
    padding: 20rpx 0;
    font-size: 28rpx;
  }
  
  .join-btn {
    flex: 2;
    background: #ff4757;
    color: white;
    border: none;
    border-radius: 8rpx;
    padding: 20rpx 0;
    font-size: 28rpx;
    font-weight: bold;
    
    &.ended {
      background: #999;
    }
  }
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx;
}
</style> 